// 注册页-业务模块
console.log( '注册页-业务模块。。。' )

import axios from 'axios'

let email = document.querySelector('#email')
let send = document.querySelector('#send')
let register = document.querySelector('#register')
let user = document.querySelector('#user')
let pass = document.querySelector('#pass')
let code = document.querySelector('#code')
let nick = document.querySelector('#nick')
let sex = document.querySelector('#sex')
let age = document.querySelector('#age')

send.onclick = function (){
    // 验证输入的邮箱格式
    let reg = /^\w{6,20}@[0-9a-zA-Z]{1,12}(\.[a-zA-Z]{2,3}){1,2}$/
    if (!reg.test(email.value)) {
        alert('邮箱格式错误！')
        return
    }
    // 发送验证码
    // axios.post('http://localhost:8080/users/sendmail',{
    axios.post('/api/users/sendmail',{
        email: email.value
    })
    .then((res)=>{
        alert(res.data.msg)
    })
}

register.onclick = function (){
    // 获取输入的数据
    let user_val = user.value
    let pass_val = pass.value
    let email_val = email.value
    let code_val = code.value
    let nick_val = nick.value
    let sex_val = sex.value
    let age_val = age.value

    // 验证账号
    var reg_user = /^\w{6,20}$/
    if (!reg_user.test(user_val)) {
        alert('账号格式错误！')
        return
    }
    // 验证密码
    var reg_pass = /^\w{6,18}$/
    if (!reg_pass.test(pass_val)) {
        alert('密码格式错误！')
        return
    }
    // 验证邮箱
    let reg_email = /^\w{6,20}@[0-9a-zA-Z]{1,12}(\.[a-zA-Z]{2,3}){1,2}$/
    if (!reg_email.test(email_val)) {
        alert('邮箱格式错误！')
        return
    }
    // 验证验证码
    var reg_code = /^\d{4,8}$/
    if (!reg_code.test(code_val)) {
        alert('验证码格式错误！')
        return
    }
    // 验证昵称
    var reg_nick = /^.{2,12}$/
    if (!reg_nick.test(nick_val)) {
        alert('昵称格式错误！')
        return
    }
    // 验证性别
    var reg_sex = /^男|女$/
    if (!reg_sex.test(sex_val)) {
        alert('性别格式错误！')
        return
    }
    // 验证年龄
    var reg_age = /^\d{1,3}$/
    if (!reg_age.test(age_val)) {
        alert('年龄格式错误！')
        return
    }

    // 发送注册请求
    // axios.post('http://localhost:8080/users/register',{
    axios.post('/api/users/register',{
        user: user_val,
        pass: pass_val,
        email: email_val,
        code: code_val,
        nickname: nick_val,
        sex: sex_val,
        age: age_val
    })
    .then((res)=>{
        alert(res.data.msg)
        if (res.data.code === 1) {
            // 注册成功，跳转到登录页面
            location.href = './login.html'
        }
    })
}